package com.ronghuanet.gift.exception.handler;

import com.ronghuanet.gift.exception.BusinessException;
import com.ronghuanet.gift.exception.code.StatusCode;
import com.ronghuanet.gift.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //通知
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)   //处理业务异常
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        log.error("error occurred!"+e.getMessage());
        return AjaxResult.me().setSuccess(false)
                .setCode(e.getCode()).setMessage(e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)   //jsr303参数异常
    public AjaxResult businessExceptionHandler(MethodArgumentNotValidException e){
        StatusCode code = StatusCode.CODE_400;
        //获取所有字段验证错误
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuilder sb = new StringBuilder();
        fieldErrors.forEach(fieldError->{
            sb.append(fieldError.getDefaultMessage()+",");
        });
        String msgStr = sb.toString();
        msgStr = msgStr.substring(0,msgStr.length()-1); //删除最后一个逗号

        log.error("error occurred!"+msgStr);
        return AjaxResult.me().setSuccess(false)
                .setCode(code.getCode()).setMessage(msgStr);
    }

    @ExceptionHandler(Exception.class)   //处理业务异常
    public AjaxResult exceptionHandler(Exception e){
        String className = e.getClass().getCanonicalName();
        if (className.endsWith("AccessDeniedException")){ //没有权限特殊处理
            StatusCode code = StatusCode.CODE_403_FORBIDDEN;
            return AjaxResult.me().setSuccess(false).setCode(code.getCode())
                    .setMessage(code.getMessage());
        }
        StatusCode code = StatusCode.CODE_500;
        e.printStackTrace();
        log.error("error occurred!"+e.getMessage());
        return AjaxResult.me().setSuccess(false).setCode(code.getCode())
                .setMessage(code.getMessage());
    }
}
